package com.ucode.hrm.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ucode.hrm.mapper.HrmCustomerCompanyMapper;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.model.hrm.HrmCustomerCompany;
import com.ucode.model.hrm.enums.HrmSysResultCodeEnum;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;

@Service
public class HrmCustomerCompanyServiceImpl implements HrmCustomerCompanyService {

    @Resource
    private HrmCustomerCompanyMapper customerCompanyMapper;

    @Override
    public HrmCustomerCompanyMapper initMapper() {
        return customerCompanyMapper;
    }

    @Override
    public Long insert(HrmCustomerCompany hrmCustomerCompany) {
        if(ObjUtil.isNull(hrmCustomerCompany.getId()))
            hrmCustomerCompany.setId(IdentifyUtils.getDefaultSnowflakeId());

        this.validateForCreateOrUpdate(true, hrmCustomerCompany);
        int i = customerCompanyMapper.insert(hrmCustomerCompany);

        return i > 0 ? hrmCustomerCompany.getId() : null;
    }

    @Override
    public int update(HrmCustomerCompany hrmCustomerCompany) {
        this.validateForCreateOrUpdate(false, hrmCustomerCompany);
        return customerCompanyMapper.update(hrmCustomerCompany);
    }

    @Override
    public int updateStatus(Collection<Long> ids, Integer status) {
        return customerCompanyMapper.updateStatus(ids, status);
    }


    /**
     * 验证数据
     * @param isInsert 是否新增
     * @param bean
     */
    private void validateForCreateOrUpdate(boolean isInsert,HrmCustomerCompany bean) {
        boolean is_validate_name = true;//是否需要验证名称的唯一性
        if(!isInsert){
            if(ObjectUtil.isNull(bean.getId()))
                throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
            HrmCustomerCompany db_bean = this.selectByPrimaryKey(bean.getId());
            if(ObjectUtil.isNull(db_bean))
                throw new UcodeServiceException(HrmSysResultCodeEnum.CUSTOMER_COMPANY_NOT_EXISTS);

            //如果跟数据库一致，代表无需验证
            is_validate_name = ObjectUtil.isNotNull(bean.getCompanyName()) && !bean.getCompanyName().equals(db_bean.getCompanyName());
        }

        if(is_validate_name && ObjectUtil.isNotNull(this.queryOneByName(bean.getCompanyName()))){
            // 校验名称的唯一性
            throw new UcodeServiceException(HrmSysResultCodeEnum.CUSTOMER_COMPANY_NAME_DUPLICATE);
        }

    }
}
